package com.liuqi.knet.rpc;

import java.io.Serializable;

/**
 * @author liuqi
 * @date 2025/3/6 15:17
 **/
public class RpcResult implements Result, Serializable {

    public static final byte SUCCESS = 0;

    private static final long serialVersionUID = -4335285085441097068L;

    private byte code;

    private Object value;

    private Throwable throwable;

    public RpcResult() {
    }

    public RpcResult(Object value) {
        this.value = value;
    }

    public RpcResult(byte code, Object value) {
        this.code = code;
        this.value = value;
    }

    public RpcResult(Throwable throwable) {
        this.throwable = throwable;
    }

    public static final RpcResult fail(String message) {
        return new RpcResult((byte) -1, message);
    }

    public static final RpcResult success(Object value) {
        return new RpcResult(value);
    }

    @Override
    public byte code() {
        return code;
    }

    @Override
    public boolean serviceSuccess() {
        return code == SUCCESS;
    }

    @Override
    public Object getValue() {
        return value;
    }

    @Override
    public Throwable getException() {
        return throwable;
    }

    @Override
    public boolean hasException() {
        return throwable != null;
    }

    @Override
    public String toString() {
        return "{" +
                "code=" + code +
                ", value=" + value +
                ", throwable=" + throwable +
                '}';
    }
}
